﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Reflection;

namespace SpringStudio.Common
{
    public static class MyGrid
    {
        /// <summary>
        /// DataSet数据集转化为HTML列表输出
        /// </summary>
        /// <param name="ds">数据集</param>
        /// <param name="template">页面列表模板</param>
        /// <param name="pageSize">每页记录条数</param>
        /// <param name="pageIndex">当前页索引</param>
        /// <returns>输出的HTML代码</returns>
        public static string DsToHtml(DataSet ds, string template, int pageSize, int pageIndex)
        {
            if (ds == null || ds.Tables.Count < 1)  // 数据集中无数据的情况
            {
                return "";
            }

            StringBuilder rtn = new StringBuilder();

            // 添加序号列
            if (!ds.Tables[0].Columns.Contains("Number"))
            {
                ds.Tables[0].Columns.Add("Number");
            }

            int number = (pageIndex - 1) * pageSize;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                number++;
                dr["Number"] = number.ToString();
                string strRecord = template;

                // 替换字段数据
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    strRecord = Regex.Replace(strRecord, "{" + dc.ColumnName + "}", dr[dc.ColumnName].ToString(), RegexOptions.IgnoreCase);
                }

                // 加入到输出
                rtn.Append("\n" + strRecord + "\n");
            }

            return rtn.ToString();
        }

        /// <summary>
        /// DataSet数据集转化为HTML列表输出
        /// </summary>
        /// <param name="ds">数据集</param>
        /// <param name="template">页面列表模板</param>
        /// <returns>输出的HTML代码</returns>
        public static string DsToHtml(DataSet ds, string template)
        {
            return MyGrid.DsToHtml(ds, template, 0, 1);
        }
    }
}
